from tools_algorithm import *


class Solution:
    def countPairs(self, nums: List[int]) -> int:

        b = [1]
        for _ in range(6):
            b.append(b[-1] * 10)

        def swap(num, i, j):
            ni, nj = num // b[i] % 10, num // b[j] % 10
            num = num - ni * b[i] - nj * b[j]
            num = num + ni * b[j] + nj * b[i]
            return num

        cnt = Counter()
        ans = 0
        for num in nums:
            ans += cnt[num]
            s = set([num])
            for i in range(6):
                for j in range(i + 1, 7):
                    snum = swap(num, i, j)
                    if snum not in s:
                        ans += cnt[snum]
                        s.add(snum)
            ss = set()
            for snum in s:
                for i in range(6):
                    for j in range(i + 1, 7):
                        ssnum = swap(snum, i, j)
                        if ssnum not in s and ssnum not in ss:
                            ans += cnt[ssnum]
                            ss.add(ssnum)
            cnt[num] += 1
        return ans
